from views.base import BaseHandler
import json
from db import db
import redis
from util.comm import md5
from util.myjwt import myjwt
from util.myredis import r
import hashlib
import time

#创建类


# def pomition():
#     def login(func):
#         def wrapper(self,*args, **kwargs):
#             # 1.获取前端token
#             headers = self.request.headers
#             print('headers',headers)
#             if not headers:
#                 return self.finish({
#                     'code':400,
#                     'msg':'获取前端token失败'
#                 })
#             #获取token
#             token = headers['headers']
#             # 2.将token拿去判断
#             flag = myjwt.jwt_check(token)
#             print('flag', flag)
#             if flag == True:
#                 # 解析验证时间
#                 payload = myjwt.jwt_de(token)
#                 ptime = payload['data']['exp']
#                 now_time = time.time()
#                 # print('now_time',now_time)
#                 if now_time - int(ptime) > 3600:
#                     self.finish({
#                         'code': 402,
#                         'user_id':payload['data']['user_id']
#                     })
#             else:
#                 self.finish({
#                     'code': 403
#                 })
#
#             func(self,*args,**kwargs)
#         return wrapper
#     return login

class ResourceHandler(BaseHandler):
    def get(self):
        # id = self.get_query_argument('role_id')
        sql = """select * from resource where pid=0 and type =1;"""
        # 获取所有资源
        res = db.findAll(sql)
        # print('res',res)
        temp = []
        for i in res:
            temp.append({
                'id':i['id'],
                'name':i['name'],
            })

        self.finish({
            'code': 200,
            'msg': '获取成功',
            'reslist': temp,
        })

class ResourceSecondHandler(BaseHandler):
    def get(self):
        pid = self.get_query_argument('rid')
        print('pid',pid)
        sql = """select * from resource where pid='%d' and type =1;"""%(int(pid))
        # 获取所有资源
        res = db.findAll(sql)
        temp = []
        for i in res:
            temp.append({
                'id':i['id'],
                'name':i['name'],
                'url':i['url']
            })

        self.finish({
            'code': 200,
            'msg': '获取成功',
            'reslist': temp,
        })

class ResourseView(BaseHandler):
    def get(self):
        #1.接收前端角色id
        role_id = self.get_query_argument('set_id')
        # print('role_id',role_id)
        #获取所有资源
        sql = """select * from resource where pid>0"""
        res = db.findAll(sql)
        # print('res',res)
        if not res:
            self.write('获取资源列表数据失败')
        data = [{'key':i['id'],"label":i['name']} for i in res]

        #此角色选择的资源
        sql1 = """select resource_id from role_resource where role_id='%d'"""%(int(role_id))
        idlist = db.findAll(sql1)
        # print('idlist',idlist)
        checklist = []
        for j in idlist:
            #将该角色所拥有的资源id添加到列表里
            checklist.append(j['resource_id'])
        mes = {'code':200,'reslist':data,'checklist':checklist}
        self.write(mes)


    def post(self):
        pass

        # id = self.get_argument('id')
        # pid = self.get_argument('pid')
        # name = self.get_argument('name')
        # # url = self.get_argument('url')
        # print('name',name,type(pid))
        # print('pid',pid,type(pid))
        #
        # # mes = json.loads(data)
        # # print('mes',mes,type(mes))
        #
        # sql = """insert into resource(id,name, pid) values('%d','%s','%d')""" %(int(id),name,int(pid))
        # db.update(sql)
        # db.commit()
        #
        # self.finish({
        #     'code':200,
        #     'msg':'添加成功'
        # })

class ResourseInfoView(BaseHandler):
    def put(self):
        id = self.get_body_argument('id')
        name = self.get_body_argument('name')
        # pid = self.get_body_argument('pid')
        # url = self.get_body_argument('url')

        if name:
            sql = f"""update resource set id = {int(id)} where name = '{name}' """
            db.update(sql)
            db.commit()

        # if pid:
        #     sql = """update resource set id = ('%d') where pid = ('%d')""" %(int(id),int(pid))
        #     db.add(sql)
        #     db.commit()
        self.finish({
            'code': 200,
            'msg': '修改成功'
        })

    def delete(self):
        id = self.get_body_argument('id')
        sql = """delete from resource where id = ('%d')""" %(int(id))
        db.update(sql)
        db.commit()
        self.finish({
            'code': 200,
            'msg': '删除成功'
        })


class RoleView(BaseHandler):
    def get(self):
        #获取参数
        sql = """select * from role;"""
        res = db.findAll(sql)
        if not res:
            self.finish({
                'code':400,
                'msg':"获取数据失败"
            })
        mes = {"code": 200, 'rolelist': res}
        self.write(mes)

    def post(self):
        data = json.loads(self.request.body)
        id = data['id']
        name = data['name']
        
        self.write("name 23is post:"+str(id)+",password is:"+name)

#用户
class UserView(BaseHandler):
    def get(self):
        sql = """select * from admin_user"""
        res = db.findAll(sql)
        if not res:
            self.finish({
                'code':400,
                'msg':'用户数据不存在'
            })

        temp = []
        for i in res:
            print('i',i)
            temp.append({
                'id':i['id'],
                'name':i['name'],
                'mobile':i['mobile'],
                'role_id':i['role_id']
            })
        self.finish({
            'code': 200,
            'msg': '获取成功',
            'data': temp
        })

    def post(self):
        data = json.loads(self.request.body)
        print('data',data)
        if not data:
            self.write('接收前端数据失败')

        name = data['name']
        mobile = data['mobile']
        password = '123456'
        password = md5(password)
        # print('password',password,type(password))
        role_id = data['value']

        if not all([name,mobile,password,role_id]):
            self.write('前端数据不完整')

        #取数据库中查询
        sql1 = """select * from admin_user where mobile=%s"""%(mobile)
        user = db.findOne(sql1)
        if user:
            return self.finish({
                'msg':'该手机号已经注册'
            })

        sql = """insert into admin_user(name, mobile,password,role_id) values('%s','%s','%s',%d)""" % (name, mobile,str(password),int(role_id))
        db.update(sql)
        db.commit()

        self.finish({
            'code': 200,
            'msg': '添加成功'
        })


#根据角色id获取资源列表的方法
def getMenu(role_id):
    # print('role_id',role_id)
    sql = "select res.*,pres.name as pname from role_resource as rr left join resource as res on rr.resource_id=res.id  inner join resource as pres on res.pid=pres.id where rr.role_id=%d" % (
        int(role_id))
    res = db.findAll(sql)
    # print('res',res)

    reslist = []
    ids = []
    pomitionlist = []
    #遍历查询结果
    for i in res:
        print('i......',i)
        pomitionlist.append(i['url'])
        print('pomitionlist', pomitionlist)
        #判断父类是否存在，不存在就添加
        if i['pid'] not in ids:
            ids.append(i['pid'])
            reslist.append({'id':i['pid'],'name':i['pname'],'son':[{'id':i['id'],'name':i['name']}]})
            # print('reslist1',reslist)
        else:
            #存在、查找父类，遍历父类用子类的pid对比
            for (index,p) in enumerate(reslist):
                if i['pid'] == p['id']:
                    #将子类加到父类下
                    reslist[index]['son'].append({'id':i['id'],'name':i['name'],'url':i['url']})
                    # print('reslist2',reslist)
    return reslist,pomitionlist

#登录
class AdminLoginView(BaseHandler):
    def post(self):
        data = json.loads(self.request.body)
        mobile = data['mobile']
        password = data['password']
        # mobile = self.get_argument('mobile')
        # password = self.get_argument('password')
        
        if not all([mobile,password]):
            self.finish({
                'code':400,
                'msg':'请输入用户名密码'
            })
        
        #取数据库查询
        sql = """select * from admin_user where mobile='%s'"""%(mobile)
        user = db.findOne(sql)
        if user:
            #密码对比
            password = md5(password)

            if password == user['password']:
                #生成token
                data = {'data':{'mobile':user['mobile'],'name':user['name'],'user_id':user['id'],'role_id':user['role_id'],'exp':time.time()}}
                token = myjwt.jwt_en(data)

                #根据角色id获取资源列表
                print('user的role_id',user['role_id'])
                menulist,pomitionlist = getMenu(user['role_id'])

                # print('menulist',menulist)
                redata = {'code':200,'token':token,'name':user['name'],'mobile':user['mobile'],'id':user['id'],'role_id':user['role_id'],'mpstatus':user['mpstatus'],'menulist':menulist,'pomitionlist':pomitionlist}
                self.finish(redata)
            else:
                self.finish({"code": 10012, "mes": "密码不正确"})

        else:
            return self.finish({
                'code':400,
                'msg':'该用户不存在'
            })

    def put(self):
        mobile = self.get_argument('mobile')
        password = self.get_argument('password')
        print('mobile',mobile)
        print('password',password)
        data = json.loads(self.request.body)
        print('data', data)
        if not data:
            self.write('接收前端数据失败')
        mobile = data['mobile']
        password = data['password']
        password = md5(password)

        sql = """select * from admin_user where mobile=%s"""%mobile
        res = db.findOne(sql)
        if not res:
            self.finish({
                'code':400,
                'msg':'手机号不存在'
            })
        else:
            user = """update admin_user set password = "%s",mpstatus="%d" where mobile = '%s'"""%(str(password),1,mobile)
            db.update(user)
            db.commit()
            self.finish({
                'code': 200,
                'msg': '密码修改成功'
            })

class IndexHandler(BaseHandler):
    def get(self):
        role_id = self.get_argument('role_id')
        sql = """select res.*,pres.name as pname from role_resource as rr left join resource as res on rr.resource_id=res.id inner join resource as pres on res.pid=pres.id where rr.role_id='%d'"""%(int(role_id))
        res = db.findAll(sql)
        print('res......',res)

        reslist = []
        ids = []
        # 遍历查询结果
        for i in res:
            #判断父类是否存在，不存在添加
            if i['pid'] not in ids:
                ids.append(i['pid'])
                reslist.append(
                    {"id": i["pid"], "name": i['pname'], "son": [{"id": i['id'], "name": i['name'], 'url': i['url']}]})
            else:
                #如果父类存在，查找父类，遍历父类用子类的pid对比
                for (index,p) in enumerate(reslist):
                    if i['pid'] == p['id']:
                        # 将子类加到父类下
                        reslist[index]['son'].append({"id": i['id'], "name": i['name'], 'url': i['url']})
                    data = {"code": 200, "menulist": reslist}
                    self.write(data)


